import axios from 'axios';

const API_BASE_URL = '/api/yijing';

export interface DivinationRequest {
  numbers: number[];
}

export interface CoinDivinationRequest {
  question?: string;
}

export interface Yao {
  value: number;
  isChanging: boolean;
}

export interface GuaXiangInfo {
  guaName: string;
  guaCi: string;
  xiangCi: string;
  yaoCi: string[];
  binary: string;
  yaos: Yao[];
}

export interface DivinationResult {
  originalGua: GuaXiangInfo;
  changingYaos: Yao[];
  changedGua?: GuaXiangInfo;
}

export interface ApiResponse<T> {
  success: boolean;
  data?: T;
  message?: string;
}

class YijingApiService {
  private client = axios.create({
    baseURL: API_BASE_URL,
    timeout: 60000, // 延长超时时间到60秒
    headers: {
      'Content-Type': 'application/json',
    },
  });

  async divination(request: DivinationRequest): Promise<ApiResponse<DivinationResult>> {
    try {
      const response = await this.client.post<DivinationResult>('/divination', request);
      return {
        success: true,
        data: response.data,
      };
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || '算卦请求失败',
      };
    }
  }

  async randomDivination(question?: string): Promise<ApiResponse<DivinationResult>> {
    try {
      const response = await this.client.post<DivinationResult>('/random', { question });
      return {
        success: true,
        data: response.data,
      };
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || '随机算卦请求失败',
      };
    }
  }

  async coinDivination(request: CoinDivinationRequest): Promise<ApiResponse<DivinationResult>> {
    try {
      const response = await this.client.post<DivinationResult>('/coin', request);
      return {
        success: true,
        data: response.data,
      };
    } catch (error: any) {
      return {
        success: false,
        message: error.response?.data?.message || '硬币算卦请求失败',
      };
    }
  }

  async healthCheck(): Promise<ApiResponse<boolean>> {
    try {
      await this.client.get('/health');
      return {
        success: true,
        data: true,
      };
    } catch (error: any) {
      return {
        success: false,
        message: '后端服务不可用',
      };
    }
  }
}

export const yijingApi = new YijingApiService();